<template>
  <!-- !租客合同 -->
  <div class="room-contact" style="height: 100%">
    <a-card size="small" style="height: 100%" v-if="hasOwner">
      <!-- 租客显示 -->
      <template v-if="currentOwner.id">
        <a-row type="flex" align="top" justify="space-between">
          <a-col>
            <a-dropdown v-if="roomOwnerList.length > 1" overlayClassName="hide-scroller-bar" :overlayStyle="{
              height: '500px',
              overflow: 'hidden auto',
              borderRadius: '10px'
            }">
              <div class="owner-name">
                <a-space>
                  <span>{{ currentOwner.owner_name }}</span>
                  <a-tag v-if="currentOwner.status == 0" color="#87d068">{{ currentOwner.owner_type }}</a-tag>
                  <a-tag v-else color="#777777">{{ currentOwner.owner_type }}</a-tag>
                  <DownOutlined />
                </a-space>
              </div>
              <template #overlay>
                <a-menu @click="onRoomOwnerChange" style="border: 1px solid #f0f0f0">
                  <a-menu-item v-for="item of roomOwnerList" :key="item.id" >
                    <span>{{ item.owner_name }}</span>
                    <a-tag style="margin-left: 10px;" v-if="item.status == 0" color="#87d068">{{ item.owner_type }}</a-tag>
                    <a-tag style="margin-left: 10px;" v-else color="#777777">{{ item.owner_type }}</a-tag>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
            <div class="owner-name" v-else>
              <span>{{ currentOwner.owner_name }}</span>
              <a-tag style="margin-left: 10px;" v-if="currentOwner.status == 0" color="#87d068">{{ currentOwner.owner_type }}</a-tag>
              <a-tag style="margin-left: 10px;" v-else color="#777777">{{ currentOwner.owner_type }}</a-tag>
            </div>
          </a-col>
          <a-col>
            <a-button type="link" @click="checkOwnerDetail">
              {{ $L("租客") }}详情
            </a-button>
          </a-col>
        </a-row>
        <!-- <a-row
          v-if="currentOwner.tag_info_arr && currentOwner.tag_info_arr.length"
        >
          <TagList :list="currentOwner.tag_info_arr" :type="2" />
        </a-row> -->
        <!-- 合同显示 -->
        <a-table
          :dataSource="contractList"
          :columns="CONTRACT_COLUMNS"
          :pagination="false"
          rowKey="id"
          :loading="contractLoading"
          size="small"
          bordered
          class="mt-10"
        >
          <template #title>
            <span>合同列表</span>
          </template>
          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key === 'contract_number'">
              <a-button type="link" @click="checkContractDetail(record)">
                {{ text }}
              </a-button>
            </template>
            <template v-if="column.key === 'rent_price'">
              <span>{{ record.rent_price + record.contract_price_unit }}</span>
            </template>
            <template v-if="column.key === 'contract_tags'">
              <template
                v-if="record.contract_tags && record.contract_tags.length"
              >
                <TagList :list="record.contract_tags" :type="2" />
              </template>
              <span v-else> -- </span>
            </template>
          </template>
        </a-table>
      </template>
    </a-card>
    <div class="no-owner" v-else>
      <a-empty description="当前房源未绑定业主" />
      <a-space class="mt-10">
        <a-button type="primary" @click="onNewContract">
          <template #icon>
            <SolutionOutlined />
          </template>
          录入租客合同
        </a-button>
        <a-button @click="onOwnerBind">
          <template #icon>
            <LinkOutlined />
          </template>
          绑定房源业主
        </a-button>
      </a-space>
    </div>

    <!-- 添加租客 -->
    <OwnerContEdit
      :visible="ownerAddVisible"
      @cancel="ownerAddVisible = false"
      @btnok="onOwnerAddSuccess"
    />

    <!-- 租客详情 -->
    <OwnerDetailDrawer
      :visible="ownerDetailVisible"
      :id="currentOwner.id"
      @cancel="onOwnerDetailClose"
    />

    <!--  合同详情  -->
    <ContractDetailDrawer
      :visible="contractDetailVisible"
      :id="contractDetailId"
      @handleCancel="
        () => {
          contractDetailVisible = false;
        }
      "
    />
  </div>
</template>
<script>
import { defineComponent, reactive, toRefs, defineAsyncComponent } from "vue";
import {
  LinkOutlined,
  SolutionOutlined,
  PlusOutlined,
  DownOutlined,
} from "@ant-design/icons-vue";
import OwnerContEdit from "../../../views/village/OwnerManage/modules/OwnerContEdit.vue";
import OwnerDetailDrawer from "../../../views/village/OwnerManage/modules/OwnerDetailDrawer.vue";
import TagList from "../../Tag/show.vue";
import request from "../../../common/utils/request";
import { message, Modal } from "ant-design-vue";
import { useRouter } from "vue-router";
import BLCOMMON from "bl-common-vue3";
const ContractDetailDrawer = defineAsyncComponent(() =>
  import("@/views/contract/ContractDetail/ContractDetailDrawer.vue")
);

const LANG = {
  owner: BLCOMMON.utils.L("租客"),
};

export default defineComponent({
  name: "RoomContracts",
  props: {
    detail: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {
    ContractDetailDrawer,
    LinkOutlined,
    SolutionOutlined,
    PlusOutlined,
    DownOutlined,
    OwnerContEdit,
    OwnerDetailDrawer,
    TagList,
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
  },
  setup(props, { emit }) {
    const ROUTER = useRouter();

    const state = reactive({
      LANG,

      roomOwnerList: [],
      currentOwner: {},
      hasOwner: true,

      contractList: [],
      contractLoading: false,

      bindOwnerId: undefined,
      bindOwner: {},
      ownerAddVisible: false,

      ownerDetailVisible: false,
      // 合同详情
      contractDetailVisible: false,
      contractDetailId: 0,
    });

    /** 查看合同详情 */
    const checkContractDetail = (record) => {
      if (record.id) {
        state.contractDetailId = record.id;
        state.contractDetailVisible = true;
      }
    };

    /** 查看租客详情 */
    const checkOwnerDetail = () => {
      state.ownerDetailVisible = true;
    };
    const onOwnerDetailClose = () => {
      state.ownerDetailVisible = false;
      getRoomOwnerList();
    };

    /** 选中租客 */
    const onRoomOwnerChange = (e) => {
      const { key } = e;
      state.currentOwner = state.roomOwnerList.find((it) => it.id == key);
      getContractInfo();
    };

    /** 绑定租客 */
    const onOwnerBind = () => {
      state.bindOwnerId = undefined;
      emit("editOwner");
    };

    const onOwnerSelect = (val, option) => {
      const { build_bind } = option;
      const { detail } = props;
      if (
        build_bind &&
        build_bind.village &&
        detail.village_id != build_bind.village.id
      ) {
        message.warning(
          `租客已经绑定【${build_bind.village.name}】项目，系统暂不支持同时绑定多个项目。`
        );
        state.bindOwnerId = undefined;
        return;
      }
      state.bindOwnerId = val;
      state.bindOwner = option;
    };

    /** 添加租客 */
    const addOwner = () => {
      state.ownerAddVisible = true;
    };
    const onOwnerAddSuccess = () => {
      state.ownerAddVisible = false;
      // 重新获取房间绑定的租客，有可能在添加租客时已经绑定
      getRoomOwnerList();
    };

    /** 录入合同 */
    const onNewContract = () => {
      console.log(props.detail);
      if (props.detail.is_lock) {
        // 如果房间已锁定
        Modal.warning({
          title: "提示",
          content: `该房间已锁定，无法录入合同！`,
          centered: true,
        });
      } else {
        emit("newContract");
      }
      // ROUTER.push({
      //   name: "addContract",
      //   query: {
      //     room_id: props.detail.id,
      //     village_id: props.detail.village_id,
      //     layer_id: props.detail.layer_id,
      //     build_id: props.detail.build_id,
      //   },
      // });
    };

    /** 获取租客列表 */
    const getRoomOwnerList = () => {
      request
        .get("/village", "/project/room/getOwnerList", {
          build_id: props.detail.build_id,
          room_id: props.detail.id,
        })
        .then((res) => {
          state.roomOwnerList = [];
          if (res.list && res.list.length > 0) {
            state.hasOwner = true;
            state.roomOwnerList = res.list;
            let index = -1;
            if (state.currentOwner.id) {
              index = state.roomOwnerList.findIndex(
                (it) => it.id == state.currentOwner.id
              );
            }
            if (index == -1) {
              index = 0;
            }
            onRoomOwnerChange({ key: res.list[index].id });
          } else {
            state.hasOwner = false;
          }
        });
    };

    /** 获取租客信息 */
    const getOwnerInfo = () => {
      request
        .get("/org", "/owner/info", {
          id: state.currentOwnerId,
        })
        .then((res) => {});
    };

    const getContractInfo = () => {
      state.contractLoading = true;
      request
        .get("/org", "/owner/contractRentData", {
          owner_id: state.currentOwner.id,
          room_id: props.detail.id,
        })
        .then((res) => {
          state.contractList = res.initData.contractList;
        })
        .finally(() => {
          state.contractLoading = false;
        });
    };

    const init = () => {
      getRoomOwnerList();
    };

    init();

    return {
      CONTRACT_COLUMNS,
      ...toRefs(state),
      onOwnerBind,
      onNewContract,
      addOwner,
      onOwnerAddSuccess,
      onOwnerSelect,
      onRoomOwnerChange,
      checkContractDetail,
      checkOwnerDetail,
      onOwnerDetailClose,
      BLCOMMON,
    };
  },
});

const CONTRACT_COLUMNS = [
  {
    title: "合同编号",
    dataIndex: "contract_number",
    key: "contract_number",
    width: 300,
  },
  {
    title: "开始日",
    dataIndex: "lease_starttime",
    key: "lease_starttime",
    width: 120,
  },
  {
    title: "结束日",
    dataIndex: "lease_endtime",
    key: "lease_endtime",
    width: 120,
  },
  {
    title: "租赁单价",
    dataIndex: "rent_price",
    key: "rent_price",
  },
  {
    title: "签订日",
    dataIndex: "sign_time",
    key: "sign_time",
    width: 120,
  },
  {
    title: "合同标签",
    dataIndex: "contract_tags",
    key: "contract_tags",
  },
  {
    title: "合同状态",
    dataIndex: "status_txt",
    key: "status_txt",
  },
];
</script>

<style lang="less" scoped>
.no-owner {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.owner-name {
  font-size: 15px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.65);
  display: flex;
  align-items: center;
}
</style>
